package net.bat.web.cyb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springside.modules.utils.PropertiesLoader;

import net.bat.entity.User;

import com.capinfo.crypt.Md5;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CybService {
	protected static PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/application.properties");

	private static String baseurl = propertiesLoader.getProperty("CYB_URL");
	//测试使用url
	//private static final String baseurl = "http://beta-v3.yuanchuangyun.com";
	/**
	 * 系统ID
	 */
	private static final String h_sys_id = "dlrxh";
	/**
	 * 注册业务ID
	 */
	private static final String h_act_id_regist = "101";
	/**
	 * 登录业务ID
	 */
	private static final String h_act_id_login = "102";
	/**
	 * 加密盐
	 */
	private static final String salt = "dlrxh123456";
	/**
	 * 测试用户
	 */
	//private static final String h_user_id = "user4";
	
	private static final String DEFAULT_PASSWORD = "111111";
	/**
	 * 创意宝注册
	 * code：0001-00是成功，0001-01是失败
	 * msg：用户已存在
	 * 用户创建失败，昵称已经存在
	 * 用户创建失败，邮箱已经存在
	 * 用户创建失败，手机号码已经存在
	 * 用户创建失败
	 * @return
	 */
	public static boolean regist(User user) {
		PrintWriter pw = null;
		InputStream is = null;
		boolean succ = false;
		try {
			HttpURLConnection urlConnection = null;
			String urlString = baseurl+"/cybIfcAction.do";
			URL url;
			url = new URL(urlString);
			urlConnection = (HttpURLConnection) url.openConnection();
			String methodString = "POST";
			urlConnection.setRequestMethod(methodString);
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setRequestProperty("Charset", "UTF-8");
			// urlConnection.setRequestProperty("Content-type","application/x-java-serialized-object");

			pw = new PrintWriter(urlConnection.getOutputStream());
			StringBuffer sb = new StringBuffer();
			// 要上传的参数
			/*
			 * 编辑数据头start
			 */
			addContentItem(sb, "h_sys_id", h_sys_id);// 系统ID
			addContentItem(sb, "h_act_id", h_act_id_regist);// action ID
			//addContentItem(sb, "h_user_id", h_user_id);// 用户ID
			//String h_user_id = user.getLoginName();
			long userid = user.getId();
			String h_user_id = String.format("%06d", userid);     
			addContentItem(sb, "h_user_id", h_user_id);// 用户ID
			String h_time = CybService.getH_time();
			addContentItem(sb, "h_time", h_time);// 申请时间
            addContentItem(sb, "h_sys_key",getH_sys_key(h_sys_id,h_act_id_regist,h_user_id,h_time));
			 
			/*
			 * 编辑数据头end
			 */

			/*
			 * 编辑数据体start
			 */
			
			// 电子邮件
            addContentItem(sb, "password", DEFAULT_PASSWORD);
            //addContentItem(sb, "email", "wangshuxin2@cnpatt.com.cn");
			addContentItem(sb, "email", user.getEmail());
			/*
			 * 编辑数据体end
			 */

			System.out.println("cybsend="+sb.toString());
			pw.print(sb.toString());
			pw.flush();
			pw.close();

			is = urlConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = "";
			StringBuilder reData = new StringBuilder();
			while ((line = br.readLine()) != null) {
				reData.append(line);
			}

			ObjectMapper objectMapper = new ObjectMapper();
			Map<String,Object> map = objectMapper.readValue(reData.toString(), Map.class);
			System.out.println("cybreceive="+reData.toString());
			String code = (String)map.get("code");
			String msg = (String)map.get("msg");
			if("0001-00".equalsIgnoreCase(code)){//注册成功
				succ = true;
			}else{
				if("0001-01".equalsIgnoreCase(code) && "用户已存在".equals(msg)){
					succ = true;
				}
			}
			return succ;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				if (pw != null)
					pw.close();
				if (is != null)
					is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return succ;
	}

	//public static String login(String dljgid,String login_name) {
	public static String login(String dljgid,long userid) {
		try {
			String urlString = baseurl+"/business/login/apiLogin.html";
			StringBuffer sb = new StringBuffer();
			//String h_user_id = "01612";
			
			addContentItem(sb, "h_sys_id", h_sys_id);
			addContentItem(sb, "h_act_id", h_act_id_login);
			//addContentItem(sb, "h_user_id", h_user_id);
			String h_user_id = String.format("%06d", userid); 
			addContentItem(sb, "h_user_id", h_user_id);
			String h_time = CybService.getH_time();
			addContentItem(sb, "h_time", h_time);
			addContentItem(sb, "h_sys_key",getH_sys_key(h_sys_id,h_act_id_login,h_user_id,h_time));
			
			//addContentItem(sb, "page", "3");
			//addContentItem(sb, "module", "5");
			addContentItem(sb, "agentCode", dljgid);
			addContentItem(sb, "page", "3");
			addContentItem(sb, "module", "2");
			sb.insert(0, urlString + "?");
			System.out.println(sb.toString());
			
			return sb.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	//public static String login(String login_name) {
	public static String login(long userid) {
		try {
			String urlString = baseurl+"/business/login/apiLogin.html";
			StringBuffer sb = new StringBuffer();
			//String h_user_id = "01612";
			
			addContentItem(sb, "h_sys_id", h_sys_id);
			addContentItem(sb, "h_act_id", h_act_id_login);
			//addContentItem(sb, "h_user_id", h_user_id);
			String h_user_id = String.format("%06d", userid); 
			addContentItem(sb, "h_user_id", h_user_id);
			String h_time = CybService.getH_time();
			addContentItem(sb, "h_time", h_time);
			addContentItem(sb, "h_sys_key",getH_sys_key(h_sys_id,h_act_id_login,h_user_id,h_time));
			
			addContentItem(sb, "page", "3");
			addContentItem(sb, "module", "5");
			// 传递代理机构标记，标识用户为代理人协会 add by zhangqiuyi 20160505
			addContentItem(sb, "agentCode", "00000");
//			addContentItem(sb, "page", "3");
//			addContentItem(sb, "module", "2");
			sb.insert(0, urlString + "?");
			System.out.println(sb.toString());
			
			return sb.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	private static void addContentItem(StringBuffer sb, String key, String value) {
		if (sb.length() == 0) {
			sb.append(key + "=" + value);
		} else {
			sb.append("&" + key + "=" + value);
		}
	}
	
	private static String getH_time(){
		Date now = new Date();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String h_time = sdf.format(now);
		return h_time;
		//return "20160415135700";
	}
	/**
	 * 系统密钥 = MD5（系统ID + 业务ID + 申请者ID + 申请时间， 加密盐）。
	 * @return
	 */
	private static String getH_sys_key(String h_sys_id,String h_act_id,String h_user_id,String h_time){
		String h_sys_key = null;
		/*
		Md5 encoderMd5 = new Md5(salt, "Md5");
		h_sys_key = encoderMd5.encode(h_sys_id+h_act_id+h_user_id+h_time);
		*/
		byte b[] = null;
		Md5 md5 = new Md5("");
		//String key = "ycy@#D@222";
		try {
			md5.hmac_Md5(h_sys_id+h_act_id+h_user_id+h_time, salt);
			b = md5.getDigest();
			h_sys_key=md5.stringify(b);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return h_sys_key;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 String jsonContent = "{\"code\":\"200\",\"msg\":\"succ\",\"data\":{\"id\":\"001\",\"userName\":\"wsx\"}}"; 
		 ObjectMapper objectMapper = new ObjectMapper();
		 try {
			Map<String,Object> map = objectMapper.readValue(jsonContent, Map.class);
			System.out.println(((Map)map.get("data")).get("id"));
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		//MD5('dlrxh'+'101'+'user'+'20160415135700','dlrxh123456')=5c19b618eb985642da6fcae7d46aeeef

		/*
		byte b[] = null;
		Md5 md5 = new Md5("");
		try {
			md5.hmac_Md5("dlrxh"+"101"+"user"+"20160415135700",salt);
			b = md5.getDigest();
			System.out.println(md5.stringify(b));
			
			Md5Util encoderMd5 = new Md5Util(salt, "Md5");
			System.out.println(encoderMd5.encode("dlrxh"+"101"+"user"+"20160415135700"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
        Date now = new Date();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String h_time = sdf.format(now);
		System.out.println(getH_time());
		
		System.out.println(String.valueOf(null));
	}
}
